package com.ias.agdis_r.activity.mine;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.toolbox.Volley;
import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListViewInterface;
import com.baoyz.swipemenulistview.SwipeMenuXListView;
import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.BaseKeyListActivity;
import com.ias.agdis_r.activity.LoginActivity;
import com.ias.agdis_r.adapter.InitAutoTaskListAdapter;
import com.ias.agdis_r.bean.auth.AuthEnum;
import com.ias.agdis_r.bean.fight.Query;
import com.ias.agdis_r.bean.fight.QueryParams;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.DataManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.manager.ServiceManage;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.module.RestfulUri;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponseHeader;
import com.ias.agdis_r.terminalmanager.restful.flight.endpoint.request.AutotaskRequest;
import com.ias.agdis_r.terminalmanager.restful.flight.endpoint.request.InitAutoTaskRequest;
import com.ias.agdis_r.terminalmanager.restful.flight.endpoint.response.AutotaskResponse;
import com.ias.agdis_r.terminalmanager.restful.flight.endpoint.response.InitAutoTaskResponse;
import com.ias.agdis_r.terminalmanager.restful.flight.vo.AutoTaskVO;
import com.ias.agdis_r.terminalmanager.restful.flight.vo.InitAutoTaskResponseVO;
import com.ias.agdis_r.terminalmanager.restful.flight.vo.InitAutoTaskVO;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.util.SecurityUtil;
import com.ias.agdis_r.util.flight.UiUtil;
import com.ias.agdis_r.volley.GsonRequest;
import com.ias.agdis_r.volley.callback.BaseOnVolleyErrorAdapter;
import com.ias.agdis_r.volley.callback.BaseOnVolleyErrorListener;
import com.ias.agdis_r.volley.callback.BaseOnVolleySuccessListener;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import me.maxwin.view.XListView;

public class ApplyActivity extends BaseKeyListActivity implements XListView.IXListViewListener {

	private ActionBar actionBar;

	private List<Query> list = new LinkedList<Query>();
	private SwipeMenuXListView mListView;
	private BaseAdapter mAdapter;

	private RequestQueue requestQueue;
	private InitAutoTaskRequest initAutoTaskRequest;
	private BaseOnVolleySuccessListener<InitAutoTaskResponse> successListener = new BaseOnVolleySuccessListener<InitAutoTaskResponse>() {

		@Override
		public void onRequestSuccess(InitAutoTaskResponse response) {
			list.clear();
			InitAutoTaskResponseVO responseVO = response.getInitAutoTaskResponseVO();
			if (responseVO != null && responseVO.getQueryParam() != null
					&& responseVO.getQueryParam().getQueryParams() != null) {
				list.addAll(responseVO.getQueryParam().getQueryParams());
			}
			mAdapter.notifyDataSetChanged();
			onDataLoaded();
		}

		@Override
		public void onRequestFailed(BaseResponseHeader header) {
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, getString(R.string.serviceError), false);
			onDataLoaded();
		}
	};
	private BaseOnVolleyErrorListener errorListener = new BaseOnVolleyErrorAdapter() {
		@Override
		public void onErrorOccurred(com.android.volley.VolleyError e) {
			String msg = "";
			if (e instanceof TimeoutError) {

				msg = DataBaseManager.getInstance().getContext().getString(R.string.request_err_timeout);
			} else if (e instanceof ServerError) {
				//显示接收消息异常
				msg = DataBaseManager.getInstance().getContext().getString(R.string.request_err_servererror);
			} else if (e instanceof NoConnectionError) {
				msg = DataBaseManager.getInstance().getContext().getString(R.string.request_err_noconnection);
			}
			toast(msg);
			onDataLoaded();
		};
	};

	private BaseOnVolleySuccessListener<AutotaskResponse> ulLockResourceSuccessListener = new BaseOnVolleySuccessListener<AutotaskResponse>() {

		@Override
		public void onRequestSuccess(AutotaskResponse response) {
			if (response.getAutoTaskResponseVO() != null) {
				toast(getString(R.string.unlockSucceed));
			} else {
				toast(getString(R.string.unlockFailed));
			}
			UiUtil.removeLoadingUiIfExist(ApplyActivity.this);

			mListView.startRefreshView();
			query();

		}

		@Override
		public void onRequestFailed(BaseResponseHeader header) {
			// TODO Auto-generated method stub
			toast(header.getErrorMessage());
			UiUtil.removeLoadingUiIfExist(ApplyActivity.this);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_apply);

		// 如果没登录
		if (!ServiceManage.getInstance().getIsLogon()) {
			gotoLoginActivity();
			finish();
			return;
		}else if (JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_AUTOAPPLY.toString())) {
		}else{
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_UPTO, getString(R.string.no_AI_T_AUTOAPPLY), false);
			finish();
		}

		requestQueue = Volley.newRequestQueue(this);

		actionBar = getActionBar();
		initactionBarApply();

		init();
	}

	@Override
	protected void onResume() {
		super.onResume();
		UiUtil.showLoadingUi(this);
		query();
	}

	private void init() {
		mListView = (SwipeMenuXListView) getListView();
		mListView.setPullLoadEnable(false);
		mListView.setXListViewListener(this);
		mAdapter = new InitAutoTaskListAdapter(this, list);
		this.setListAdapter(mAdapter);
//		registerForContextMenu(mListView);
		
		initSwipeMenu();

		mListView.setOnMenuItemClickListener(new SwipeMenuListViewInterface.OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
				if(index == 0){
					unLockResource(position);
				}
				return false;
			}
		});
	}

	private void initSwipeMenu() {

		SwipeMenuCreator creator = new SwipeMenuCreator() {

			@Override
			public void create(SwipeMenu menu) {
				// create "open" item
				SwipeMenuItem openItem = new SwipeMenuItem(
						getApplicationContext());
				// create "delete" item
				SwipeMenuItem deleteItem = new SwipeMenuItem(
						getApplicationContext());
				// set item background
				deleteItem.setBackground(new ColorDrawable(0XFFFF0000));
				// set item width
				deleteItem.setWidth(dp2px(120));
				// set a icon
				deleteItem.setIcon(R.drawable.trash);
				// add to menu
				menu.addMenuItem(deleteItem);
			}
		};

		mListView.setMenuCreator(creator);
	}

	private int dp2px(int i) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, i, getResources().getDisplayMetrics());
	}

	private void query() {
		if (initAutoTaskRequest == null) {
			initRequest();
		}
		Request<InitAutoTaskResponse> request = null;
		try {
			request = new GsonRequest<InitAutoTaskResponse>(
                    RestfulUri.getUri(MessageModel.INIT_TTAQ), InitAutoTaskResponse.class,
                    DataManager.getInstance().getMapper().writeValueAsString(this.initAutoTaskRequest), this.successListener, this.errorListener);
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}
		requestQueue.add(request);
	}

	private void initRequest() {
		if (initAutoTaskRequest == null) {
			initAutoTaskRequest = new InitAutoTaskRequest();
		}
		initAutoTaskRequest.setHeader(SecurityUtil.getCommonRequestHeaderObject(MessageModel.INIT_TTAQ));
		initAutoTaskRequest.setInitAutoTaskVO(new InitAutoTaskVO());
	}

	@SuppressLint("InflateParams")
	private void initactionBarApply() {
		actionBar.setCustomView(LayoutInflater.from(ApplyActivity.this).inflate(R.layout.actionbar_apply, null));
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		actionBar.setDisplayShowCustomEnabled(true);
		ImageView back = (ImageView) findViewById(R.id.actionbar_apply_back);
		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		ImageView add = (ImageView) findViewById(R.id.iv_add);
		add.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(ApplyActivity.this, ApplySettingActivity.class));
			}
		});
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
		menu.setHeaderTitle(getString(R.string.chooseOperat));
		menu.add(0, (int) adapterContextMenuInfo.id, 0, getString(R.string.unlock));
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		unLockResource(item.getItemId());
		return super.onContextItemSelected(item);
	}

	private void unLockResource(int itemId) {
		UiUtil.showLoadingUi2(this);

		Query query = list.get(itemId);

		AutotaskRequest autotaskRequest = new AutotaskRequest();
		autotaskRequest.setHeader(SecurityUtil.getCommonRequestHeaderObject(MessageModel.TTAQ));
		AutoTaskVO autoTaskVO = new AutoTaskVO();
		autoTaskVO.setOpe("N");

		QueryParams params = new QueryParams();

		List<Query> queries = new ArrayList<Query>();
		queries.add(query);
		params.setQueryParams(queries);

		autoTaskVO.setParams(params);

		autotaskRequest.setAutoTaskVO(autoTaskVO);

		Request<AutotaskResponse> request = null;
		try {
			request = new GsonRequest<AutotaskResponse>(RestfulUri.getUri(MessageModel.TTAQ),
                    AutotaskResponse.class, DataManager.getInstance().getMapper().writeValueAsString(autotaskRequest), this.ulLockResourceSuccessListener,
                    this.errorListener);
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}

		requestQueue.add(request);
	}

	/**
	 * 显示提示信息，跳转到登录界面
	 */
	private void gotoLoginActivity() {
		EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, getString(R.string.use_function_tologin), false);
		Intent intent = new Intent(this, LoginActivity.class);
		this.startActivity(intent);
	}

	@Override
	public void onRefresh() {
		query();
	}

	@Override
	public void onLoadMore() {
	}

	/**
	 * 数据加载完成的后续处理
	 */
	private void onDataLoaded() {
		String str = getFormatedTimeForHearder();

		UiUtil.removeLoadingUiIfExist(this);
		mListView.stopRefresh();
		mListView.stopLoadMore();
		mListView.setRefreshTime(str);
	}

	/**
	 * 获取格式化的当前时间
	 * 
	 * @return时间格式“HH:mm:ss”
	 */
	@SuppressLint("SimpleDateFormat")
	private String getFormatedTimeForHearder() {
		SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
		Date curDate = new Date(System.currentTimeMillis());
		return formatter.format(curDate);
	}

	private void toast(String msg) {
		if (S.isNotEmpty(msg)) {
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, msg, false);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(null != requestQueue)
		requestQueue.stop();
	}
}
